<template>
  <view class='box'>
    <uni-title type="h1" :title="activity.title"></uni-title>
    <view class="secondTit">{{ activity.overview }}</view>
    <view class="applyTime">
      <view style="margin-bottom: 10rpx;">报名时间: 截止至 {{ service.style.time(activity.startTime, 8) }}</view>
      <view class="">活动时间: {{
          service.style.time(activity.startTime, 8) + "- " + service.style.time(activity.endTime, 8)
        }}
      </view>
    </view>

    <view class="whiteCard">
      <view class="left">
        <uni-title type="h3" title="活动地址"></uni-title>
        <view class="address">{{ activity.location.address }}</view>
      </view>
      <button class="navBtn" size="mini" plain @tap="handleMapLocation">
        <uni-icons type="location-filled" color="#4cd964" size="18"></uni-icons>
        导航
      </button>
    </view>

    <view class="content">
      <uni-segmented-control
          :current="current"
          :values="items"
          style-type="text"
          active-color="#3cc51f"
          @clickItem="onClickItem"
      />
      <view v-show="current === 0" class="selectBox" style="padding-top: 20rpx;">
        <rich-text :nodes="activity.content"></rich-text>
      </view>
      <view v-show="current === 1" class="selectBox" style="padding-top: 40rpx;">
        <view class="caption larTit">
          <text>报名人员</text>
          <text>总人数: {{peopleList.total}} </text>
          <text>报名日期</text>
        </view>

        <view
            class="list"
            v-for="(val,i) in peopleList.list"
            :key="val.id"
            v-if="peopleList.list.length !== 0"
        >
          <view class="leftImg">
            <view class="image">
              <image :src="val.avatar" mode="aspectFill"></image>
            </view>
            <view class="midTit">{{ val.nick }}</view>
          </view>
          <view class="rightTime midTit">{{ service.style.time(val.createTime,9) }}</view>
        </view>
        <view class="touchBottom" v-else>当前暂无报名人员</view>
      </view>
      <view class="touchBottom">- 已经到底啦 -</view>
    </view>

    <!-- 付费报名弹窗 -->
    <uni-popup ref="popup" background-color="#fff" class="payPop" @change="change">
      <view class="advPrice">报名费:
        <text style="color: red;">￥{{ activity.cost }}</text>
      </view>
      <!-- <view class="line"></view> -->

      <radio-group name="pay" @change="payWay">
        <view class="plotAddressBorder between">
          <view class="center_vertical">
            <view>
              <image src="https://www.tdtye.com/files/vegetable_mall_file/default/static/growVegetables/pay_icon.png" class="icon"></image>
            </view>
            <view>
              微信支付
            </view>
          </view>
          <view>
            <radio :value=1 style="vertical-align: sub;"/>
          </view>
        </view>
        <view class="plotAddressBorder between">
          <view class="center_vertical">
            <view>
              <image src="https://www.tdtye.com/files/vegetable_mall_file/default/static/growVegetables/wallet_icon.png" class="icon">
              </image>
            </view>
            <view>
              余额支付
            </view>
          </view>
          <view>
            <radio :value=0 style="vertical-align: sub;"/>
          </view>
        </view>
      </radio-group>

      <button type="default" @click="subOrder" class="payBtn">立即支付</button>

    </uni-popup>

    <button type="default" class="bottomBtn noStart" v-if="activity.isStart">活动已结束</button>
    <button type="default" class="bottomBtn noStart" v-else-if="activity.isOver">活动进行中</button>
    <button type="default" class="bottomBtn noStart" v-else-if="activity.isSignUp">已报名</button>
    <button type="default" class="bottomBtn start" v-else @click="activeBtn">马上报名</button>
  </view>
</template>

<script>
import service from "@/utils/service";

export default {
  data() {
    let _vm = this;
    return {
      // 活动
      items: ['活动详情', '报名人员'],
      current: 0,
      show: true,
      /* 支付方式 0:余额 1:微信 */
      payMethod: -1,
      peopleList: {
        list: [],
        total: 0,
      }, //报名人员

      service: service,
      /* 活动对象 */
      activity: {
        id: '',
        /* 活动标题 */
        title: '',
        /* 活动背景图 */
        banner: '',
        /* 活动简介 */
        overview: '',
        /* 活动详情 富文本 */
        content: '',
        /* 开始时间 */
        startTime: '',
        /* 结束时间 */
        endTime: '',
        /* 地址信息 */
        location: {
          /* 文本 */
          address: '',
          /* 纬度 */
          lat: '',
          /* 经度 */
          lng: '',
        },
        /* 是否收费 0 免费 1收费 */
        hasCost: 0,
        /* 活动报名费用 */
        cost: '',
        /* 最大报名人数 */
        registerCount: -1,

        /* 是否已经开始 */
        isStart: false,
        /* 是否已经结束 */
        isOver: false,
        /* 是否已经报名 */
        isSignUp: false
      },
      /* 加载对象 */
      loading: {
        // 进度
        plan: 0,
        // 阈值
        threshold: 0,
        step() {
          if (++this.plan >= this.threshold) {
            try {
              service.executeTask(function () {
                _vm.activity.isStart = service.check.isAfter(_vm.activity.startTime);
              })
              service.executeTask(function () {
                _vm.activity.isOver = service.check.isAfter(_vm.activity.endTime);
              })
              _vm.isSignUp();
            } catch (e) {
              console.log(" loading.step() err :  ", e)
            } finally {
              uni.hideLoading();
            }
          }
        }
      },
    }
  },
  onLoad(e) {
    console.log("页面传参 json : ", e)
    if (!service.check.isNull(e)
        && !service.check.isNull(e.id)) {
      this.activity.id = e.id;
    }
    // 活动详情 + 报名人员列表
    this.loading.threshold = 2;
  },
  onShow() {
    uni.showLoading({
      mask: true
    });
    this.getDetail();
    this.getPeople();
  },
  methods: {
    /* 获取活动详情*/
    getDetail() {
      let _t = this;
      this.$axios({
        url: `user/public/activity/detail`,
        method: "post",
        data: {id: _t.activity.id}
      }).then((res) => {
        console.log(" user/public/activity/detail :  ", res);
        if (res.code === 0) {
          let errorFields = [];
          service.executeTask(function () {
            _t.activity.title = res.result.title;
          }, errorFields, "活动标题")

          service.executeTask(function () {
            _t.activity.banner = _t.imgApi + res.result.banner;
          }, errorFields, "北京图像")

          service.executeTask(function () {
            _t.activity.overview = res.result.overview;
          }, errorFields, "活动简介")

          service.executeTask(function () {
            _t.activity.content = res.result.content;
            if (!_t.activity.content.includes("style")) {
              _t.activity.content = _t.activity.content.replaceAll(/\<img/gi,
                  '<img style="max-width:100%;height:auto"');
            }
            if (!_t.activity.content.includes(_t.imgApi)) {
              _t.activity.content = _t.activity.content.replaceAll(/src="/gi, 'src=' + '\"' + _t.imgApi);
            }
            console.log(_t.activity.content)
          }, errorFields, "活动详情")

          service.executeTask(function () {
            _t.activity.startTime = res.result.openTime;
            _t.activity.endTime = res.result.overTime;
          }, errorFields, "活动时间")

          service.executeTask(function () {
            _t.activity.location.address = res.result.address;
            _t.activity.location.lat = res.result.lat;
            _t.activity.location.lng = res.result.lng;
          }, errorFields, "活动地址")

          service.executeTask(function () {
            _t.activity.registerCount = res.result.registerCount;
          }, errorFields, "支持报名人数")

          service.executeTask(function () {
            _t.activity.hasCost = res.result.hasCost;
          }, errorFields, "是否收费")

          service.executeTask(function () {
            if (_t.activity.hasCost === 1) {
              _t.activity.cost = res.result.cost;
            }
          }, errorFields, "报名费用")

          if (errorFields.length !== 0) {
            console.log("获取失败的参数 : ", errorFields)
          }
        }
      }).finally(() => {
        _t.loading.step();
      })
    },

    // 导航
    handleMapLocation() {
      let _t = this;
      console.log('进入导航')
      let latitude = Number(this.activity.location.lat);
      let longitude = Number(this.activity.location.lng);
      let address = this.activity.location.address
      // 获取定位信息
      uni.getLocation({
        type: 'wgs84', //返回可以用于uni.openLocation的经纬度
        // 用户允许获取定位
        success: function (res) {
          console.log(res, '经纬度===>', latitude, longitude)
          if (res.errMsg == "getLocation:ok") {
            uni.openLocation({
              // 传入你要去的纬度
              latitude: latitude,
              // 传入你要去的经度
              longitude: longitude,
              // 传入你要去的地址信息 不填则为空
              address: address,
              // 缩放大小
              scale: 10,
              success: function () {
                console.log('成功的回调success');
              }
            });
          }
        },
        // 用户拒绝获取定位后 再次点击触发
        fail: function (res) {
          console.log(res)
          if (res.errMsg == "getLocation:fail auth deny") {
            uni.showModal({
              content: '检测到您没打开获取信息功能权限，是否去设置打开？',
              confirmText: "确认",
              cancelText: '取消',
              success: (res) => {
                if (res.confirm) {
                  uni.openSetting({
                    success: (res) => {
                      console.log('确定');
                    }
                  })
                } else {
                  console.log('取消');
                  return false;
                }
              }
            })
          }
        }
      });
    },
    change(e) {
      console.log('当前模式：' + e.type + ',状态：' + e.show);
    },

    /* 获取报名人员 */
    getPeople() {
      let _t = this;
      this.$axios({
        url: 'user/usActivity/registerPeople',
        method: "post",
        data: {
          id: _t.activity.id,
        }
      }).then((res) => {
        console.log(' user/usActivity/registerPeople : ', res)
        if (res.code === 0) {
          _t.peopleList.list = res.result.list;
          _t.peopleList.total = res.result.total;
        } else {
          uni.showToast({
            title: '获取报名人员失败,请重试',
            icon: 'none',
          })
        }
      }).finally(() => {
        _t.loading.step();
      })
    },
    // 报名弹窗
    activeBtn() {
      // 判断用户是否登录
      let token = uni.getStorageSync('token');
      if (service.check.isNull(token)) {
        uni.showToast({
          title: '您当前还没有登录,请先登录.',
          icon: 'none',
          duration: 2000
        })
        uni.navigateTo({
          url: `/pages/mine/loginPage`
        })
        return;
      }
      if (this.activity.hasCost === 1) {
        // 付费报名
        this.$refs.popup.open('bottom')
      } else {
        // 免费报名
        this.joinActive()
      }
    },
    // 免费报名
    joinActive(method = 0) {
      let _t = this;
      let activeId = this.activity.id;
      uni.showLoading({
        title: "报名中...."
      })
      this.$axios({
        url: `user/usActivity/register`,
        method: "post",
        data: {id: activeId,method : method}
      }).then((res) => {
        console.log(" user/usActivity/register :  ", res)
        if (res.code === 0) {
          uni.showToast({
            title: "报名成功"
          })
          _t.getPeople();
        }
      }).finally(() => {
        service.executeTask(function () {
          _t.isSignUp();
        })
        uni.hideLoading()
      })
    },
    // 活动
    onClickItem(e) {
      if (this.current !== e.currentIndex) {
        this.current = e.currentIndex
      }
    },
    //单选事件
    payWay(e) {
      this.payMethod = Number(e.detail.value)
    },
    //提交订单，点击提交订单按钮的时候加一个加载图标的全局遮罩，等请求完成后再放开
    subOrder() {
      let _t = this;
      switch (this.payMethod) {
        case 0:
          this.balancePay(_t.activity.id);
          break;
        case 1:
          console.log("微信支付")
          this.wechatPaySignUp()
          break;
        case -1:
          uni.showToast({
            title: "请选择支付方式",
            icon: 'none',
            duration: 2000
          });
          break;
        default:
          uni.showToast({
            title: "支付方式错误",
            icon: 'none',
            duration: 2000
          });
      }
    },
    // 余额支付报名
    balancePay(id) {
      let _t = this;
      uni.showLoading({
        title: "余额支付中......"
      })
      this.$axios({
        url: `user/usActivity/payBalance`,
        method: "post",
        data: {id}
      }).then((res) => {
        if (res.code === 0) {
          uni.showToast({
            title: "报名成功",
            duration: 2000
          })
        } else {
          uni.showToast({
            title: res.result,
            icon: 'none',
            duration: 2000
          })
        }
      }).finally(() => {
        uni.hideLoading();
        this.$refs.popup.close();
        _t.getPeople();
      })
    },
    // 微信支付报名
    wechatPaySignUp(){
      let _t = this;
      uni.showLoading({
        title: '生成报名记录中.....',
        mask: true
      })
      this.$axios({
        url: `user/usActivity/wechatPaySignUp`,
        method: "post",
        data: {activityId: _t.activity.id}
      }).then(async res => {
        console.log(" user/usActivity/wechatPaySignUp :  ", res);
        if(res.code === 0){
          /* 生成报名记录成功 根据记录唯一编号 创建微信订单 */
          let wxOrderRes = await service.request.createWxOrder(res.result,5,this.$axios)
          if(wxOrderRes.code === 0){
            service.request.wxPayment(wxOrderRes.result,
              function success(res){
                console.log("微信支付报名成功 : " ,res)
                uni.showToast({
                  title: '报名成功',
                  duration: 4000,
                  mask: true
                })
              },
              function fail(res){
                console.log("微信支付报名失败...")
                uni.showToast({
                  title: '支付失败,可以在 "我的中心" -> "活动记录" 中重新支付',
                  duration: 4000,
                  icon: 'none',
                })
              }
            )
          }
        }else{
          uni.showToast({
            title: res.result,
            duration: 3000,
            icon: 'none'
          })
        }
      }).finally(() => {
        service.executeTask(function () {
          _t.isSignUp();
        })
        uni.hideLoading();
        this.$refs.popup.close();
        _t.getPeople();
      })
    },

    // 用户是否已经报名
    isSignUp(){
      let _t = this;
      this.$axios({
        url: `user/usActivity/isSignUp`,
        method: "post",
        data: {activityId: _t.activity.id}
      }).then(res => {
        console.log(" user/usActivity/isSignUp :  " , res)
        if(res.code === 0){
          _t.activity.isSignUp = res.result;
        }
      })
    }
  },
}
</script>

<style lang='scss' scoped>
/deep/ .uni-title__box {
  padding-top: 0 !important;
}

.payBtn {
  margin: 50rpx 0 30rpx;
  border-radius: 100rpx;
  background: #3cc51f;
  color: #fff;
}

.advPrice {
  font-weight: bold;
  font-size: 32rpx;
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
}

.payWay {
}

.line {
  width: 100%;
  margin: 30rpx 0;
  height: 1rpx;
  background: #eee;
}

.icon {
  width: 50rpx;
  height: 50rpx;
  margin-right: 20rpx;
  margin-top: 10rpx;
}

.plotAddressBorder {
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 0.5rpx solid #eeeeee;
}

/deep/ .vue-ref {
  border-radius: 20rpx 20rpx 0 0;
}

/deep/ .uni-popup .uni-popup__wrapper {
  border-radius: 20rpx 20rpx 0 0;
  padding: 20rpx;
}

.payPop {
  z-index: 100;
}

/deep/ .segmented-control {
  height: 100rpx !important;
  font-weight: bold;
}

/deep/ .segmented-control__text {
  font-size: 36rpx !important;
}

.box {
  min-height: 100vh;
  background-color: #fff;
  padding: 20rpx;

  .secondTit {
    font-size: 30rpx;
    color: #999;
    margin-bottom: 20rpx;
  }

  .applyTime {
    font-size: 25rpx;
    color: #999;
    margin: 20rpx 0 40rpx;
  }

  .whiteCard {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left {
      width: 65%;

      .address {
        color: #999;
        font-size: 28rpx;
      }
    }

    .navBtn {
      border-radius: 100rpx;
      border: 2rpx solid #4cd964;
      color: #4cd964;
      height: 70rpx;
      line-height: 70rpx;
      margin-right: 0;
    }
  }

  .content {
    padding-top: 20rpx;
    padding-bottom: 100rpx;

    .selectBox {
      padding-top: 20rpx;
    }

    .touchBottom {
      font-size: 25rpx;
      color: #999;
      text-align: center;
      margin-top: 20rpx;
    }

    .caption {
      display: flex;
      justify-content: space-between;
    }

    .list {
      min-height: 100rpx;
      line-height: 100rpx;
      display: flex;
      justify-content: space-between;

      .leftImg {
        display: flex;
        align-items: center;

        .image {
          width: 50rpx;
          height: 50rpx;
          border-radius: 50%;
          overflow: hidden;
          border: 2rpx solid #eee;
          margin-right: 10rpx;

          image {
            width: 100%;
            height: 100%;
            vertical-align: top;
          }
        }
      }
    }
  }

  .litTit {
    font-size: 25rpx;
    color: #999;
  }

  .midTit {
    font-size: 28rpx;
    color: #999;
  }

  .larTit {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
  }

  .noStart {
    color: #fff;
    background-color: #999999;
  }

  .start {
    color: #fff;
    background-color: #3cc51f;
  }
}
</style>
